﻿using MediatR;
using WMS.Common;
using WMS.Domain;
using WMS.Infrastructure;
using System.Linq;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using WMS.Api.Application.Commands;

namespace WMS.Api.Application.CommandHandlers
{
    public class QueryProductmarginsHander : IRequestHandler<QueryProductmarginsCommand, PagingResult<List<Productmargins>>>
    {
        IBaseRepository<Productmargins> _productmarginsbase;

        public QueryProductmarginsHander(IBaseRepository<Productmargins> productmarginsbase)
        {
            _productmarginsbase = productmarginsbase;
        }

        public async Task<PagingResult<List<Productmargins>>> Handle(QueryProductmarginsCommand request, CancellationToken cancellationToken)
        {
            // 使用GetNewAllList方法获取查询对象
            var query = _productmarginsbase.GetNewAllList();
            
            // 应用筛选条件
            if (!string.IsNullOrEmpty(request.Team))
            {
                query = query.Where(p => p.Team == request.Team);
            }

            if (!string.IsNullOrEmpty(request.OutboundCode))
            {
                query = query.Where(p => p.OutboundCode == request.OutboundCode);
            }

            if (request.Time.HasValue)
            {
                var date = request.Time.Value.Date;
                query = query.Where(p => p.Time.Date == date);
            }

            // 执行分页查询
            var total = query.Count();
            var items = await query
                .OrderByDescending(p => p.Time)
                .Skip((request.PageIndex - 1) * request.PageSize)
                .Take(request.PageSize)
                .ToListAsync();

            // 返回分页结果
            return new PagingResult<List<Productmargins>>
            {
                data = items,
                totalCount = total,
                totalPage = (int)Math.Ceiling(total / (double)request.PageSize)
            };
        }
    }
}
